﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Dynamic;
using System.Net;
using System.Text;
using System.Threading.Tasks;

using Microsoft.SharePoint.Client;

namespace SharepointPlugin
{
    public class BizRules
    {
        [ThreadStatic]
        static ClientContext s_context;

        protected static ClientContext Context(Models.SpointConnectionInfo info)
        {
            if (s_context == null)
            {
                s_context = new ClientContext(info.SiteUrl);
                s_context.Credentials = new System.Net.NetworkCredential(info.UserId, info.Pwd);
            }
            return s_context;

        }

        public static void DisposeContext()
        {
            if (s_context != null)
            {
                s_context.Dispose();
                s_context = null;
            }
        }

        public static System.IO.Stream getDocumentStream(Models.SpointConnectionInfo info, string url)
        {
            WebClient client = new WebClient();
            client.Credentials = new System.Net.NetworkCredential(info.UserId, info.Pwd);
            return client.OpenRead(info.SiteUrl + url);
        }

        public static List<Models.Article> GetArticles(Models.SpointConnectionInfo info, string pageListName=null)
        {
            if (string.IsNullOrWhiteSpace(pageListName))
                pageListName = "Site Pages";

            List<Models.Article> articles = new List<Models.Article>();

            using (ClientContext context = Context(info))
            {
                List pages = context.Web.Lists.GetByTitle(pageListName);
                CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
                ListItemCollection items = pages.GetItems(query);

                // Retrieve all items in the ListItemCollection from List.GetItems(Query). 
                context.Load(items);
                context.ExecuteQuery();
                foreach (ListItem listItem in items)
                {
                    string title = listItem["FileLeafRef"].ToString();
                    title = title.Substring(0, title.Length - 5);
                    articles.Add(new Models.Article() { Id = listItem.Id, Title = title, Body = (string)listItem["WikiField"] });
                }
            }
            return articles;
        }


        public static Models.Article GetArticle(Models.SpointConnectionInfo info, int id, string pageListName = null)
        {
            Models.Article a = null;
            if (string.IsNullOrWhiteSpace(pageListName))
                pageListName = "Site Pages";
            using (ClientContext context = Context(info))
            {
                List pages = context.Web.Lists.GetByTitle(pageListName);
                ListItem page = pages.GetItemById(id);
                context.Load(page);
                context.ExecuteQuery();
                if (page != null)
                {
                    string title = page["FileLeafRef"].ToString();
                    title = title.Substring(0, title.Length - 5);
                    a = new Models.Article() { Id = id, Title = title, Body = page["WikiField"].ToString() };
                }

                return a;
            }
        }

        public static List<Models.SpointItem> GetListItems(Models.SpointConnectionInfo info, string listName)
        {
            List<Models.SpointItem> items = new List<Models.SpointItem>();
            using (ClientContext context = Context(info))
            {
                List itemList = context.Web.Lists.GetByTitle(listName);
                context.Load(itemList);
                ListItemCollection ilcol = itemList.GetItems(CamlQuery.CreateAllItemsQuery());
                context.Load(ilcol);
                context.ExecuteQuery();
                foreach (ListItem item in ilcol)
                {
                    ExpandoObject idy = new ExpandoObject();
                    var x = idy as IDictionary<string, Object>;
                    foreach (string name in item.FieldValues.Keys)
                        if(item[name] != null)
                            x[name] = item[name];    //[buff.AppendFormat("<li>{0}:{1}</li>", name, listItem[name]);
                    items.Add(new Models.SpointItem() { BaseTemplate = itemList.BaseTemplate, BaseType = (int)itemList.BaseType, Item = idy });
                }
            }
            return items;
        }

        public static Models.SpointItem GetListItem(Models.SpointConnectionInfo info, string listName, int id)
        {
            using (ClientContext context = Context(info))
            {
                List itemList = context.Web.Lists.GetByTitle(listName);
                context.Load(itemList);
                ListItem item = itemList.GetItemById(id);
                context.Load(item);
                context.ExecuteQuery();

                if(itemList.BaseType == BaseType.Survey)
                {
                    if (itemList.BaseTemplate == (int)ListTemplateType.Tasks) ;
                }


                ExpandoObject idy = new ExpandoObject();
                var x = idy as IDictionary<string, Object>;
                foreach (string name in item.FieldValues.Keys)
                    if (item[name] != null)
                        x[name] = item[name];    //[buff.AppendFormat("<li>{0}:{1}</li>", name, listItem[name]);

                return new Models.SpointItem() { BaseTemplate = itemList.BaseTemplate, BaseType = (int)itemList.BaseType, Item = idy };
            }
        }
    }
}
